<template>
  <!-- <div class="mainTitle">{{ dialogTitle }}占比</div> -->
  <ContentWrap>
    <el-button @click="submitForm" type="primary" :disabled="formLoading">保存</el-button>
    <el-button @click="goBack">关闭</el-button>
  </ContentWrap>
  <ContentWrap>
    <div class="subTitle">基本信息</div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :inline="true"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="产品类型" prop="productId">
        <el-select 
          v-model="productType"
          placeholder="请选择产品类型"
          filterable
          remote
          value-key="id"
          @change="changeProduct"
          :remote-method="remoteProductMethod"
          :loading="productLoading"
          :disabled="formType === 'update'"
        >
          <el-option
            v-for="item in productList"
            :key="item.id"
            :label="item.productType"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="dictComponentStatus">
        <el-select
          v-model="formData.dictComponentStatus"
          placeholder="请选择状态"
          clearable
          class="!w-220px"
        >
          <el-option
            v-for="dict in getIntDictOptions('config_remark_status')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品占比" prop="proportion">
        <el-input disabled v-model="formData.proportion" />
      </el-form-item>
      <el-form-item label="备注" prop="productRemark">
        <el-input v-model="formData.productRemark" placeholder="请输入产品备注" />
      </el-form-item>
    </el-form>
    <div class="subTitle">占比配置</div>
    <el-table border v-loading="loading" :data="list" :tree-props="{ children: 'children' }" default-expand-all row-key="treeId" :height="contentHeight">
      <el-table-column label="部件类型" align="left" prop="partType" />
      <el-table-column label="工序名称" align="left" prop="dictProcessName" >
        <template #default="scope">
          <dict-tag type="craft_process_name" :value="scope.row.dictProcessName" />
        </template>
      </el-table-column>
      <el-table-column label="占比" align="left" prop="proportion">
        <template #default="scope">
          <el-input-number @change="changeProportion" v-model="scope.row.proportion" :precision="2" :step="0.01" :min="0" :max="100" />
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
</template>
<script setup lang="ts">
import { getIntDictOptions } from '@/utils/dict'
import * as DrawingComponentRemarkApi from '@/api/config/drawingComponentRemark'
import { useTagsViewStore } from '@/store/modules/tagsView'
interface querys {
  type: string
  id: string
}
interface ProductOption {
  id: number
  productType: string
}
const { currentRoute } = useRouter()
const { query } = useRoute()
const contentHeight = ref(0)

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const productLoading = ref(false)
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const loading = ref(false)  //占比配置加载
const list = ref([])  //占比配置列表
const productList = ref<ProductOption[]>([]) //产品类型列表
const productType = ref<ProductOption>()
const formData = ref({
  dictComponentStatus: 10,
  productId: undefined,
  id: undefined,
  productType: undefined,
  productRemark: undefined,
  proportion: 0,
  type: 1
})
const formRules = reactive({
  productId: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
  dictComponentStatus: [{ required: true, message: '产品状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

// 返回
const route = useRouter() // 路由
const tagsViewStore = useTagsViewStore()
const goBack = () => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(currentRoute.value)
  route.push({
    path: '/config/config/proportion/list'
  })
}

/** 初始化 */
const open = async (type: string, id: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id !== 'undefined') {
    formLoading.value = true
    loading.value = true
    try {
      const res = await DrawingComponentRemarkApi.getDrawingComponentRemarkUnit({id})
      list.value = res.children.map((item, index) => {
        item.treeId = index
        item.children.map((child, childIndex) => {
          child.treeId = childIndex + Math.random()
          return child
        })
        return item
      })
      let proportion = 0
      res.children.map(item => {
        proportion += parseFloat(item.proportion || 0)
      })
      formData.value = {
        dictComponentStatus: res.dictComponentStatus,
        productId: res.productId,
        id: res.id,
        productRemark: res.productRemark,
        productType: res.productType,
        proportion: proportion,
        type: 1
      }
      productType.value = {
        id: res.productId,
        productType: res.productType
      }
      productList.value = [{
        id: res.productId,
        productType: res.productType
      }]
    } finally {
      formLoading.value = false
      loading.value = false
    }
  }
}

// 获取产品类型
const remoteProductMethod = async (query: string) => {
  if (query) {
    productLoading.value = true
    try {
      productList.value = await DrawingComponentRemarkApi.getDrawingComponentProduct(query)
    } finally {
      productLoading.value = false
    }
  } else {
    productList.value = []
  }
}

// 修改占比
const changeProportion = () => {
  let sum = 0
  list.value.map(item => {
    sum += (parseFloat(item['proportion']) || 0)
  })
  formData.value.proportion = sum
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  let sum = 0
  for (let i = 0; i < list.value.length; i++) {
    if (!list.value[i]['proportion']) {
      message.notifyError('部件占比不能为空或等于0')
      return
    }
    sum += parseFloat(list.value[i]['proportion'] || 0)
    // 工序占比之和
    let processSum = 0
    for(let j = 0; j < list.value[i].children.length; j++) {
      if (!list.value[i]['children'][j]['proportion']) {
        message.notifyError('工序占比不能为空或等于0')
        return
      }
      processSum += parseFloat(list.value[i]['children'][j]['proportion'] || 0)
    }
    if (processSum > 100) {
      message.notifyError(`${list.value[i]['partType']}工序占比之和不能大于100%`)
      return
    }
    if (processSum < 100) {
      message.notifyError(`${list.value[i]['partType']}工序占比之和不能小于100%`)
      return
    }
  }
  if (sum > 100) {
    message.notifyError('部件占比之和不能大于100%')
    return
  }
  if (sum < 100) {
    message.notifyError('产品占比之和不能小于100%')
    return
  }
  formLoading.value = true
  loading.value = true
  try {
    formData.value.proportion = sum
    if (formType.value === 'create') {
      const drawingComponentRemarkCreateReqVOS = list.value.map(item => {
        return {
          partType: item['partType'],
          id: item['id'],
          componentId: item['componentId'],
          proportion: item['proportion'],
          drawingComponentRemarkCreateReqVOS: item['children']
        }
      })
      const productData = {
        ...formData.value,
        drawingComponentRemarkCreateReqVOS
      }
      await DrawingComponentRemarkApi.createDrawingComponentRemark(productData)
      message.success(t('common.createSuccess'))
    } else {
      let processData = []
      let componentData = list.value.map(item => {
        item.children.map(child => {
          processData.push(child)
        })
        return {
          type: item['type'],
          proportion: item['proportion'],
          productType: item['productType'],
          productRemark: item['productRemark'],
          productId: item['productId'],
          partType: item['partType'],
          parentId: item['parentId'],
          id: item['id'],
          dictComponentStatus: item['dictComponentStatus'],
          componentId: item['componentId']
        }
      })
      await DrawingComponentRemarkApi.updateDrawingComponentRemark([...processData, ...componentData, formData.value])
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    goBack()
  } finally {
    formLoading.value = false
    loading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    dictComponentStatus: 10,
    productId: undefined,
    id: undefined,
    productType: undefined,
    productRemark: undefined,
    proportion: 0,
    type: 1
  }
  formRef.value?.resetFields()
}

// 改变产品类型
const changeProduct = async (val) => {
  formData.value.productId = val.id
  formData.value.productType = val.productType
  const actionType = query.type
  // 不是清空时
  if (val) {
    if (actionType === 'update') {
      const res = await DrawingComponentRemarkApi.getDrawingComponentRemarkUnit({id: val.id})
      if (res.length) {
        list.value = res[0].childList
      } else {
        list.value = []
      }
    } else if (actionType === 'create') {
      const data = await DrawingComponentRemarkApi.getDrawingComponentRemarkUnitCreate(val.id)
      list.value = data.map((item, index) => {
        item.proportion = 0
        item.treeId = index
        item.children.map((child, childIndex) => {
          child.treeId = childIndex + Math.random()
          return child
        })
        return item
      })
    }
  }
}

onMounted(() => {
  contentHeight.value = document.body.clientHeight - 132 - formRef.value.$el.clientHeight - 160
  const { type, id } = currentRoute.value.query as unknown as querys
  open(type, id)
})
</script>
<style lang="scss" scoped>
.mainTitle {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
}

.subTitle {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
}
</style>
